package za.org.jcicada.genss;

import java.io.Serializable;
import java.net.URI;
import java.net.URISyntaxException;

public class PhysicalURN implements Serializable {

	/** Serial version ID */
	private static final long serialVersionUID = 1L;

	/** Identifying physical URNs */
	public static final String URN_PHYSICAL = "physical";
	
	/** Cache the root URN */
	private static PhysicalURN ROOT_URN;
	
	/** The path part of the URN */
	private final String path;

	/** The actual URN is stored in a URI */
	private final URI physicalURI;
	
	static {
		try {
			ROOT_URN = new PhysicalURN("/");
		} catch (URISyntaxException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	/**
	 * Constructor given a path
	 * 
	 * @param path with nodes separated by /
	 * @throws URISyntaxException
	 */
	public PhysicalURN(String path) throws URISyntaxException {
		String start = URN_PHYSICAL + "/";
		if (path.startsWith(start)) {
			path = path.substring(start.length());
		}
		if (path.length() == 0) {
			path = "/";
		}
		path = path.replaceAll("//", "/");
		if (!path.matches("^/.*")) {
			throw new URISyntaxException(path, "Must start with /");
		}
		if (path.contains("//")) {
			throw new URISyntaxException(path, "May not contain //");
		}
		if (path.contains(".")) {
			throw new URISyntaxException(path, "May not contain .");
		}
		this.path = path;
		physicalURI = new URI(String.format("%s/%s", URN_PHYSICAL, path));
	}

	public String getPath() {
		return path;
	}
	
	public String getName() {
		return path.substring(path.lastIndexOf('/'));
	}

	@Override
	public String toString() {
		return physicalURI.toString();
	}

	@Override
	public boolean equals(Object aOther) {
		if (this == aOther)
			return true;
		if (!(aOther instanceof PhysicalURN))
			return false;
		PhysicalURN other = (PhysicalURN) aOther;
		return physicalURI.equals(other.physicalURI);
	}

	@Override
	public int hashCode() {
		return physicalURI.hashCode();
	}
	
	public static PhysicalURN getRootURN() {
		return ROOT_URN;
	}
}
